package com.jeesite.modules.task.feedback.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.action.entity.DcSupTaskAction;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfo;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoService;
import com.jeesite.modules.task.receive.web.TaskReceiveController;
import com.jeesite.modules.utils.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.task.feedback.entity.DcSupTaskFeedback;
import com.jeesite.modules.task.feedback.dao.DcSupTaskFeedbackDao;
import com.jeesite.modules.file.utils.FileUploadUtils;

import javax.swing.*;

/**
 * 任务反馈信息表Service
 * @author zrr
 * @version 2022-03-02
 */
@Service
@Transactional(readOnly=false)
public class DcSupTaskFeedbackService extends CrudService<DcSupTaskFeedbackDao, DcSupTaskFeedback> {

	@Autowired
	private DcSupTaskFeedbackDao dcSupTaskFeedbackDao;
	@Autowired
	private DcSupTaskActionDao dcSupTaskActionDao;
	@Autowired
	private DcSupTaskInfoService dcSupTaskInfoService;
	/**
	 * 获取单条数据
	 * @param dcSupTaskFeedback
	 * @return
	 */
	@Override
	public DcSupTaskFeedback get(DcSupTaskFeedback dcSupTaskFeedback) {
		return super.get(dcSupTaskFeedback);
	}
	
	/**
	 * 查询分页数据
	 * @param dcSupTaskFeedback 查询条件
	 * @return
	 */
	@Override
	public Page<DcSupTaskFeedback> findPage(DcSupTaskFeedback dcSupTaskFeedback) {
		return super.findPage(dcSupTaskFeedback);
	}
	
	/**
	 * 查询列表数据
	 * @param dcSupTaskFeedback
	 * @return
	 */
	@Override
	public List<DcSupTaskFeedback> findList(DcSupTaskFeedback dcSupTaskFeedback) {
		return super.findList(dcSupTaskFeedback);
	}

	/**
	 * 根据id列表 查询部分反馈列表
	 * status 反馈状态
	 */
	public List<DcSupTaskFeedback> findListWithActionIds(List<String> actionId,String status){
		return dcSupTaskFeedbackDao.findListWithActionIds(actionId,status);
	}


	/**
	 * 根据id列表 查询所有反馈列表
	 */
	public List<DcSupTaskFeedback> findListFeedbacks(List<String> actionId){
		return dcSupTaskFeedbackDao.findListFeedbacks(actionId);
	}

	/**
	 * 根据action查询最近需要反馈的时间
	 */
	public List<DcSupTaskFeedback> findLastTaskFeedback(List<String> actionId){
		if (actionId==null||actionId.size()==0){
			return new ArrayList<DcSupTaskFeedback>();
		}
		return dcSupTaskFeedbackDao.findLastTaskFeedback(actionId);
	}

	
	/**
	 * 保存数据（插入或更新）
	 * @param dcSupTaskFeedback
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(DcSupTaskFeedback dcSupTaskFeedback) {
		super.save(dcSupTaskFeedback);
		// 保存上传图片
//		FileUploadUtils.saveFileUpload(dcSupTaskFeedback, dcSupTaskFeedback.getId(), "dcSupTaskFeedback_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(dcSupTaskFeedback, dcSupTaskFeedback.getId(), "dcSupTaskFeedback_file");
	}
	
	/**
	 * 更新状态
	 * @param dcSupTaskFeedback
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(DcSupTaskFeedback dcSupTaskFeedback) {
		super.updateStatus(dcSupTaskFeedback);
	}
	
	/**
	 * 删除数据
	 * @param dcSupTaskFeedback
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(DcSupTaskFeedback dcSupTaskFeedback) {
		super.delete(dcSupTaskFeedback);
	}

    public List<DcSupTaskFeedback> findListOverRide(DcSupTaskFeedback dcSupTaskFeedback) {
		return dcSupTaskFeedbackDao.findListOverRide(dcSupTaskFeedback);
    }
    public List<Map<String,String>> findListOverRideStr(DcSupTaskFeedback dcSupTaskFeedback) {
		return dcSupTaskFeedbackDao.findListOverRideStr(dcSupTaskFeedback);
    }
    public DcSupTaskFeedback getOverRide(DcSupTaskFeedback dcSupTaskFeedback) {
		return dcSupTaskFeedbackDao.getOverRide(dcSupTaskFeedback);
    }

    public void updateFeedbackStatusById(String id,String feedbackStatus) {
		DcSupTaskFeedback feedback = new DcSupTaskFeedback();
		feedback.setId(id);
		feedback.setFeedbackStatus(feedbackStatus);
//		feedback.setUpdateBy(UserUtils.getUser().getUserCode());
		feedback.setUpdateDate(new Date());
		dcSupTaskFeedbackDao.updateFeedbackStatusById(feedback);
    }

	public Page<DcSupTaskFeedback> listDataOverRide(DcSupTaskFeedback dcSupTaskFeedback) {
		List<DcSupTaskFeedback> list = dcSupTaskFeedbackDao.listDataOverRide(dcSupTaskFeedback);
		for (int i = 0; i < list.size(); i++) {
			if(!"1".equals(list.get(i).getFeedbackStatus())&&TaskReceiveController.DateCompare(list.get(i).getFeedbackEndTime(),list.get(i).getFeedbackTime())){
				list.get(i).setRemarks2("逾期反馈");
			}else{
				list.get(i).setRemarks2("已反馈");
			}
			if(list.get(i).getFeedbackStatus().equals("1")){
				list.get(i).setRemarks2("草稿");
			}
		}
		return dcSupTaskFeedback.getPage().setList(list);
	}

	public Page<DcSupTaskFeedback> feedbacklistData(DcSupTaskFeedback dcSupTaskFeedback) {
		List<DcSupTaskFeedback> list = dcSupTaskFeedbackDao.feedbacklistData(dcSupTaskFeedback);
		//根据开始时间给按钮权限
//		for (int i = 0; i < list.size(); i++) {
//			if(list.get(i).getFeedbackStartTime().getTime()<System.currentTimeMillis()){
//				list.get(i).setColour("green");
//			}else{
//				list.get(i).setColour("");
//			}
//		}
		String time = LocalDateTime.now().plusDays(3).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		for (int i = 0; i < list.size(); i++) {
			int res=time.compareTo(list.get(i).getFeedbackStartTimeStr());
			if(!StringUtils.equals(list.get(i).getFeedbackStatus(),"2")&&!StringUtils.equals(list.get(i).getFeedbackStatus(),"3")&&!StringUtils.equals(list.get(i).getFeedbackStatus(),"5")&&!StringUtils.equals(list.get(i).getFeedbackStatus(),"9")&&!StringUtils.equals(list.get(i).getFeedbackStatus(),"11")&&res>=0){
				list.get(i).setColour("open");
			}
		}
		if((dcSupTaskFeedback.getIsWatch()==null?0:dcSupTaskFeedback.getIsWatch())==1) {
			list.forEach(s -> {
				if (Dict.FeedbackStatus.STATUS_1.equals(s.getFeedbackStatus())) {
					s.setFeedbackStatus("-1");
				}
			});
		}
		return dcSupTaskFeedback.getPage().setList(list);
	}

	public Integer queryOverTimeCount(DcSupTaskFeedback dcSupTaskFeedback) {
		return dcSupTaskFeedbackDao.queryOverTimeCount(dcSupTaskFeedback);
	}

	public Page<DcSupTaskFeedback> queryfeedbackHistory(DcSupTaskFeedback dcSupTaskFeedback) {
		List<DcSupTaskFeedback> list = dcSupTaskFeedbackDao.queryfeedbackHistory(dcSupTaskFeedback);
		return dcSupTaskFeedback.getPage().setList(list);
	}

	/**
	 * @describe 处理业务逻辑之前调用,查询是第一次反馈还是最后一次反馈,0,第一次反馈,1最后一次反馈,-1反馈途中或反馈完成
	 * @param actionId
	 * @return
	 */
	public Integer isFirstOrLast(String actionId){
		DcSupTaskFeedback feedback = new DcSupTaskFeedback();
		feedback.setActionId(actionId);
		List<DcSupTaskFeedback> list = dcSupTaskFeedbackDao.findList(feedback);
		long listSize = list.size();
		long isFirst = 0;
		long isLast = 0;
		isFirst = list.stream().filter(s -> "-1".equals(s.getFeedbackStatus())||"1".equals(s.getFeedbackStatus())).count();
		isLast = list.stream().filter(s -> !"-1".equals(s.getFeedbackStatus())&&!"1".equals(s.getFeedbackStatus())).count();
		if(listSize==isLast+1 || listSize==1){
			return 1;
		}else if(listSize==isFirst){
			return 0;
		}else{
			return -1;
		}
	}

	/**
	 * 判断当前分发任务的反馈是否已审核完
	 * @param actionId
	 * @return
	 */
	public Boolean isZeroAuditFeedback(String actionId){
		// 获取当前分发任务的未审核通过反馈列表
		DcSupTaskFeedback feedback = new DcSupTaskFeedback();
		feedback.setActionId(actionId);
		List<DcSupTaskFeedback> list = dcSupTaskFeedbackDao.isZeroAuditFeedback(feedback);
		if (list != null && list.size() > 0) {
			return false;
		} else {
			return true;
		}
	}

	public List<DcSupTaskFeedback> findListWithActionIds(List<String> actionId, Object o) {
		return null;
	}

    public DcSupTaskInfo getInfoByActionId(String id) {
		return dao.getInfoByActionId(id);
    }

    public void updateLastFeedback(String feedbackStatus, String id) {
		dao.updateLastFeedback(feedbackStatus,id);
    }

	public void updateActionStatus(String taskStatus,String id) {
		dao.updateActionStatus(taskStatus,id);
	}
	public void updateActionStatus2(String taskStatus,String taskProgress,String id) {
		dao.updateActionStatus2(taskStatus,taskProgress,id);
	}

    public void updateFeedbackProgress(DcSupTaskFeedback feedback) {
		dao.updateFeedbackProgress(feedback);
    }

    public DcSupTaskFeedback getNewFeedbackByActionId(String actionId) {
		return dao.getNewFeedbackByActionId(actionId);
    }

	public void addFeedbackFunc(DcSupTaskFeedback dcSupTaskFeedback) {
		DcSupTaskFeedback feedback = new DcSupTaskFeedback();
		feedback.setTaskId(dcSupTaskFeedback.getTaskId());
		feedback.setActionId(dcSupTaskFeedback.getActionId());
		feedback.setFeedbackEndTime(dcSupTaskFeedback.getFeedbackEndTime());
		feedback.setFeedbackStartTime(DateUtils.parseDate(dcSupTaskFeedback.getFeedbackEndTimeStr()));
		feedback.setFeedbackStatus(dcSupTaskFeedback.getFeedbackStatus());
		feedback.setFeedbackRequire("新增反馈");
		dcSupTaskFeedbackDao.insert(feedback);
		//修改action和info表的task_status
		if(StringUtils.equals(dcSupTaskFeedback.getFeedbackStatus(),"-1")){
			DcSupTaskAction action = new DcSupTaskAction();
			action.setId(dcSupTaskFeedback.getActionId());
			DcSupTaskAction dcSupTaskAction = dcSupTaskActionDao.get(action);
			if(StringUtils.equals(dcSupTaskAction.getTaskStatus(),"4")){
				dao.updateActionFeedbak(dcSupTaskFeedback.getActionId());
			}
			DcSupTaskInfo dcSupTaskInfo = dcSupTaskInfoService.get(dcSupTaskFeedback.getTaskId());
			if(StringUtils.equals(dcSupTaskInfo.getTaskStatus(),"9")){
				dao.updateInfoFeedbak(dcSupTaskFeedback.getTaskId());
			}
		}
	}
	@Transactional(readOnly=false)
    public void caculateTaskScore(){
		//查询逾期未反馈的数据
		Integer currentYear = Integer.parseInt(DateUtils.getYear());
		dao.deleteCurrentYearTaskScore(currentYear);
		List<Map<String,Object>> nofeedBack_list = dao.queryNofeedBackList(currentYear);
		if(nofeedBack_list != null && nofeedBack_list.size()>0 ){
			//计算扣分
			for(Map map : nofeedBack_list){
				map.put("score",0.5);
				map.put("reason","逾期未反馈");
				map.put("score_id", IdGen.nextId());
				map.put("create_date",new Date());
				dao.insertTaskScore(map);
			}
		}

		//查询逾期已反馈反馈的数据
		List<Map<String,Object>> feedBacked_list = dao.queryfeedBackedList(currentYear);
		if(feedBacked_list != null && feedBacked_list.size()>0 ){
			//计算扣分
			for(Map map : feedBacked_list){
				map.put("score",0.2);
				map.put("reason","逾期反馈");
				map.put("score_id", IdGen.nextId());
				map.put("create_date",new Date());
				dao.insertTaskScore(map);
			}
		}
		//查询未逾期的反馈状态
		List<Map<String,Object>> last_list_no = dao.queryfeedBackedListProgress(currentYear);
		if(last_list_no != null && last_list_no.size()>0 ){
			//计算扣分
			for(Map map : last_list_no){
				String process =(String)map.get("feedback_progress");
				if(StringUtils.equals("2",process)){
					map.put("score",1);
					map.put("reason","滞后时序");
				}
				else if(StringUtils.equals("4",process)){
					map.put("score",2);
					map.put("reason","未完成");
				}else{
					continue;
				}
				map.put("score_id", IdGen.nextId());
				map.put("create_date",new Date());
				dao.insertTaskScore(map);
			}
		}

	}
}